// src/http/decorators/http.ts
import { http } from "@kit.NetworkKit";
import { httpInterceptor } from "./interceptor";
import { HttpRequestConfig, HttpResponse } from "./types";

export function Get(target: object, propertyKey: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;

  descriptor.value = async function (...args: any[]) {
    // 如果被 @MyMock 装饰器处理过，直接返回
    if (typeof original !== 'function') {
      return original.apply(this, args);
    }

    const config = await httpInterceptor.applyRequestInterceptors({
      url: args[0],
      options: {
        method: http.RequestMethod.GET,
        extraData: args[1],
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        expectDataType: http.HttpDataType.OBJECT,
      },
      extraData: args[1]
    });

    return new Promise((resolve, reject) => {
      const httpRequest = http.createHttp();
      httpRequest.request(config.url, config.options, async (err, data) => {
        const response = await httpInterceptor.applyResponseInterceptors({ err, data });
        if (response.err) {
          reject(response.err);
        } else {
          resolve(response.data?.result);
        }
      });
    });
  };
}

export function Post(target: object, propertyKey: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;

  descriptor.value = async function (...args: any[]) {
    // 如果被 @MyMock 装饰器处理过，直接返回
    if (typeof original !== 'function') {
      return original.apply(this, args);
    }

    const config = await httpInterceptor.applyRequestInterceptors({
      url: args[0],
      options: {
        method: http.RequestMethod.POST,
        extraData: args[1],
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        expectDataType: http.HttpDataType.OBJECT,
      },
      extraData: args[1]
    });

    return new Promise((resolve, reject) => {
      const httpRequest = http.createHttp();
      httpRequest.request(config.url, config.options, async (err, data) => {
        const response = await httpInterceptor.applyResponseInterceptors({ err, data });
        if (response.err) {
          reject(response.err);
        } else {
          resolve(response.data?.result);
        }
      });
    });
  };
}